import { ref, computed, watch, readonly } from 'vue'
import type { Ref } from 'vue'
import type { EditorTab } from '../../../types/editor'

/**
 * 活跃标签页追踪器 - 统一管理当前活跃标签页状态
 * 
 * 功能：
 * 1. 监听globalActiveId和focusedGroupId的变化
 * 2. 提供当前活跃标签页的响应式引用
 * 3. 提供获取活跃标签页的方法
 * 4. 支持标签页变化的回调通知
 */
export function useActiveTabTracker(
  globalActiveId: Ref<string | null>,
  focusedGroupId: Ref<string | null>,
  findGroup: (root: any, groupId: string) => any,
  layoutRoot: Ref<any>
) {
  const activeTab = ref<EditorTab | null>(null)
  const activeGroup = ref<any>(null)
  
  // 活跃标签页变化回调列表
  const changeCallbacks = new Set<(tab: EditorTab | null, prevTab: EditorTab | null) => void>()
  
  // 获取当前活跃标签页
  function getCurrentActiveTab(): EditorTab | null {
    if (!globalActiveId.value || !focusedGroupId.value) {
      return null
    }
    
    const group = findGroup(layoutRoot.value, focusedGroupId.value)
    if (!group || !group.tabs) {
      return null
    }
    
    return group.tabs.find((tab: EditorTab) => tab.id === globalActiveId.value) || null
  }
  
  // 获取当前活跃分组
  function getCurrentActiveGroup() {
    if (!focusedGroupId.value) {
      return null
    }
    
    return findGroup(layoutRoot.value, focusedGroupId.value)
  }
  
  // 更新活跃标签页状态
  function updateActiveTab() {
    const prevTab = activeTab.value
    const newTab = getCurrentActiveTab()
    const newGroup = getCurrentActiveGroup()
    
    activeTab.value = newTab
    activeGroup.value = newGroup
    
    // 如果标签页发生变化，通知所有回调
    if (prevTab !== newTab) {
      changeCallbacks.forEach(callback => {
        try {
          callback(newTab, prevTab)
        } catch (error) {
          console.warn('[ActiveTabTracker] Callback error:', error)
        }
      })
    }
  }
  
  // 监听活跃标签页ID变化
  watch([globalActiveId, focusedGroupId], () => {
    updateActiveTab()
  }, { immediate: true })
  
  // 监听布局根变化（处理标签页关闭等情况）
  watch(layoutRoot, () => {
    updateActiveTab()
  }, { deep: true })
  
  // 添加标签页变化回调
  function onActiveTabChange(callback: (tab: EditorTab | null, prevTab: EditorTab | null) => void) {
    changeCallbacks.add(callback)
    
    // 返回取消监听的函数
    return () => {
      changeCallbacks.delete(callback)
    }
  }
  
  // 计算属性：当前是否有活跃标签页
  const hasActiveTab = computed(() => activeTab.value !== null)
  
  // 计算属性：当前活跃标签页的路径
  const activeTabPath = computed(() => activeTab.value?.path || null)
  
  // 计算属性：当前活跃标签页是否有文件路径
  const activeTabHasPath = computed(() => {
    return activeTab.value?.path && activeTab.value.path.trim() !== ''
  })
  
  return {
    // 响应式状态
    activeTab: readonly(activeTab),
    activeGroup: readonly(activeGroup),
    hasActiveTab,
    activeTabPath,
    activeTabHasPath,
    
    // 方法
    getCurrentActiveTab,
    getCurrentActiveGroup,
    onActiveTabChange,
    updateActiveTab
  }
}

export type ActiveTabTracker = ReturnType<typeof useActiveTabTracker>